import React from "react";
import {Tree} from "antd";
import DirPresenter from "../../.gen/presenter/DirPresenter";
import BaseComponent from "../../redare/components/BaseComponent";

export default class DirectoryTree extends BaseComponent {

    constructor(props) {
        super(props);
        this.state = {
            treeData: [
                // {title: 'Expand to load', key: '0'},
                // {title: 'Expand to load', key: '1'},
                // {title: 'Tree Node', key: '2', isLeaf: true},
            ]
        }

        this.presenter = new DirPresenter(this);
    }

    componentDidMount() {
        this.presenter.findDirectory({},{},(result)=>{
            if (result.data){
                this.setState({"treeData":result.data});
            }
        })
    }

    setValue(value) {
    }

    // updateTreeData(list, key, children) {
    //     return list.map(node => {
    //         if (node.key === key) {
    //             return {
    //                 ...node,
    //                 children,
    //             };
    //         }
    //         if (node.children) {
    //             return {
    //                 ...node,
    //                 children: this.updateTreeData(node.children, key, children),
    //             };
    //         }
    //         return node;
    //     });
    // }

    updateTreeData(list, key, children) {
        return list.map(node => {
            if (node.key === key) {
                return {
                    ...node,
                    children,
                };
            }
            if (node.children) {
                return {
                    ...node,
                    children: this.updateTreeData(node.children, key, children),
                };
            }
            return node;
        });
    }


    // onLoadData = (node) =>{
    //     this.presenter.findDirectory({},{path:node.key},(result)=>{
    //         if (result.data){
    //             this.updateTreeData(this.state.treeData, node.key,result.data)
    //         }
    //     })
    // }

    onLoadData = ({key, children}) =>
        new Promise(resolve => {
            if (children) {
                resolve();
                return;
            }
            this.presenter.findDirectory({},{path:key},(result)=>{
                if (result.data){
                    this.setState({
                        treeData: this.updateTreeData(this.state.treeData, key, result.data)
                    })
                }
                resolve();
            })
        });


    render() {
        return (
            <Tree loadData={this.onLoadData} treeData={this.state.treeData}/>
        );
    }

}